<template>
  <scroll-view class="flex-col page mine" scroll-y @scroll="onPageScroll">
    <view class="flex-col section" :style="{ paddingTop: navHeight + 'px' }">
      <xlm-top-nav :scrollTop="scrollTop" title="成绩上屏" />
      
      <!-- 用户信息卡片循环 -->
      <view v-for="(user, index) in userList" :key="user.id" class="user-card" @click="toggleUserCard(index)">
        <view class="user-header">
          <view class="user-info">
            <image :src="user.avatar || imgUrl + 'avatar1@2x.png'" class="user-avatar" />
            <text class="user-name">{{ user.name }}</text>
          </view>
          <view class="expand-icon" :class="{ expanded: expandedCards[index] }">
            <text class="icon">{{ expandedCards[index] ? '▼' : '▶' }}</text>
          </view>
        </view>
        
        <!-- 展开的比赛详情 -->
        <view v-if="expandedCards[index]" class="event-details">
          <view class="event-card">
            <image :src="user.eventInfo?.image || imgUrl + 'a.jpg'" class="event-image" />
            <view class="event-info">
              <text class="event-title">{{ user.eventInfo?.title || '北京市朝阳区全民健身羽毛球公开赛' }}</text>
              <text class="event-location">比赛地点: {{ user.eventInfo?.location || '这里是比赛的地点' }}</text>
            </view>
          </view>
          
                     <!-- 成绩列表 -->
           <view class="score-list">
             <view v-for="(score, scoreIndex) in user.scoreList" :key="scoreIndex" 
                   class="score-item" 
                   :class="{ active: user.selectedScoreIndex === scoreIndex }"
                   @click.stop="selectScore(user, scoreIndex)">
               <text class="score-distance">{{ score.distance }}</text>
               <text class="score-event">{{ score.event }}</text>
               <text class="score-category">{{ score.category }}</text>
               <text class="score-value">{{ score.value }}</text>
               <text class="score-rank">{{ score.rank }}</text>
             </view>
           </view>
          
                     <!-- 上屏按钮 -->
           <view class="display-section">
             <button class="display-btn" @click.stop="submitToDisplay(user)">
               <text class="display-btn-text">成绩上屏</text>
               <text class="queue-info">
                 {{ getSelectedScoreText(user) }} | 排队: {{ user.queueCount || queueCount }}位
               </text>
             </button>
           </view>
        </view>
      </view>
    </view>
    
    <!-- <movable-area class="movable-area" >
      <movable-view class="fab-container" direction="all" :x="x" :y="y" @tap="getNewsCustomer">
        <image :src="imgUrl + 'customerService2.png'" class="fab-icon" />
      </movable-view>
    </movable-area> -->
  </scroll-view>
</template>

<script setup>
  import { ref, computed, onMounted } from 'vue'
  import { useOutsideAppStore } from '@/store/app'
  import { imgUrl } from '@/utils/config'
  import { formatTime } from '@/utils/dateUtils.js'
  import { useRequest } from '@/api';
  import { onShow } from '@dcloudio/uni-app';
  
  const appStore = useOutsideAppStore()
  const navHeight = computed(() => appStore.navHeight)
  const scrollTop = ref(0)
  
  const onPageScroll = (e) => {
    scrollTop.value = e.detail.scrollTop
  }
  
  const { API_SCORE_DISPLAY_POST } = useRequest()
  
  // 默认排队人数
  const queueCount = ref(32)
  
     // 用户列表数据
   const userList = ref([
     {
       id: 1,
       name: '吴涛',
       avatar: '',
       eventInfo: {
         title: '北京市朝阳区全民健身羽毛球公开赛暨2024年春季运动会',
         location: '这里是比赛的地点，具体地址：北京市朝阳区某某街道某某号体育馆',
         image: ''
       },
       scoreList: [
                  {
            distance: '1000M',
            event: '长跑',
            category: '公开男子组暨2024年春季运动会',
            value: '12.33',
            rank: '冠军'
          },
                  {
            distance: '1000M',
            event: '长跑',
            category: '公开男子组暨2024年春季运动会暨全民健身活动',
            value: '12.45',
            rank: '亚军'
          },
         {
           distance: '1000M',
           event: '长跑',
           category: '公开男子组',
           value: '12.67',
           rank: '季军'
         },
         {
           distance: '1000M',
           event: '长跑',
           category: '公开男子组',
           value: '12.89',
           rank: '第四名'
         }
       ],
       selectedScoreIndex: 0, // 默认选中第一项成绩
       queueCount: 32
     },
    {
      id: 2,
      name: '梓宸',
      avatar: imgUrl + 'avatar2@2x.png',
      eventInfo: {
        title: '北京市海淀区青少年游泳锦标赛暨2024年夏季游泳比赛',
        location: '海淀游泳馆，地址：北京市海淀区中关村大街1号',
        image: ''
      },
      scoreList: [
        {
          distance: '50M',
          event: '自由泳',
          category: '青少年组',
          value: '28.45',
          rank: '冠军'
        },
        {
          distance: '100M',
          event: '蝶泳',
          category: '青少年组',
          value: '1:05.23',
          rank: '亚军'
        }
             ],
       selectedScoreIndex: 0, // 默认选中第一项成绩
       queueCount: 15
     },
     {
       id: 3,
       name: '王五',
       avatar: imgUrl + 'avatar3@2x.png',
       eventInfo: {
         title: '北京市西城区篮球联赛暨2024年春季篮球锦标赛',
         location: '西城体育馆，地址：北京市西城区西单北大街120号',
         image: ''
       },
       scoreList: [
         {
           distance: '全场',
           event: '篮球',
           category: '成年组',
           value: '89:76',
           rank: '胜利'
         }
       ],
       selectedScoreIndex: 0, // 默认选中第一项成绩
       queueCount: 8
     }
  ])

  // 展开状态控制 - 根据用户数量动态生成
  const expandedCards = ref(userList.value.map((_, index) => index === 0))

     // 切换用户卡片展开状态
   const toggleUserCard = (index) => {
     expandedCards.value[index] = !expandedCards.value[index]
   }

   // 选择成绩项
   const selectScore = (user, scoreIndex) => {
     user.selectedScoreIndex = scoreIndex
   }

   // 获取选中的成绩文本
   const getSelectedScoreText = (user) => {
     if (user.selectedScoreIndex !== undefined && user.scoreList[user.selectedScoreIndex]) {
       const selectedScore = user.scoreList[user.selectedScoreIndex]
       return `${selectedScore.distance} ${selectedScore.event} ${selectedScore.rank}`
     }
     return '请选择成绩'
   }

     // 提交成绩上屏
   const submitToDisplay = async (user) => {
     try {
       // 检查是否选择了成绩
       if (user.selectedScoreIndex === undefined || user.selectedScoreIndex < 0) {
         uni.showToast({
           title: '请先选择要上屏的成绩',
           icon: 'none'
         })
         return
       }

       const selectedScore = user.scoreList[user.selectedScoreIndex]
       if (!selectedScore) {
         uni.showToast({
           title: '选中的成绩无效',
           icon: 'none'
         })
         return
       }

       uni.showLoading({ title: '提交中...' })
       
       const params = {
         user_id: user.id,
         event_id: user.eventInfo?.id,
         score: selectedScore, // 只提交选中的成绩
         score_index: user.selectedScoreIndex
       }
       
       const res = await API_SCORE_DISPLAY_POST(params)
       
       if (res.code === 1) {
         uni.showToast({
           title: '提交成功',
           icon: 'success'
         })
         // 更新排队人数
         user.queueCount = res.data.queue_count || user.queueCount
       } else {
         uni.showToast({
           title: res.msg || '提交失败',
           icon: 'none'
         })
       }
     } catch (error) {
       console.error('提交成绩上屏失败:', error)
       uni.showToast({
         title: '提交失败，请重试',
         icon: 'none'
       })
     } finally {
       uni.hideLoading()
     }
   }

     // 添加新用户
   const addUser = (userData) => {
     const newUser = {
       id: Date.now(), // 临时ID
       name: userData.name || '新用户',
       avatar: userData.avatar || '',
       eventInfo: userData.eventInfo || {
         title: '新比赛',
         location: '比赛地点',
         image: ''
       },
       scoreList: userData.scoreList || [],
       selectedScoreIndex: 0, // 默认选中第一项成绩
       queueCount: userData.queueCount || 0
     }
     
     userList.value.push(newUser)
     expandedCards.value.push(false) // 新用户默认收起
   }

  // 删除用户
  const removeUser = (index) => {
    userList.value.splice(index, 1)
    expandedCards.value.splice(index, 1)
  }

  // 更新用户信息
  const updateUser = (index, userData) => {
    Object.assign(userList.value[index], userData)
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      // 这里可以调用API获取用户信息
      // const res = await API_GET_USER_INFO()
      // if (res.code === 1) {
      //   userList.value = res.data.map(user => ({
      //     ...user,
      //     expanded: false
      //   }))
      //   expandedCards.value = userList.value.map(() => false)
      // }
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }

  // 获取比赛信息
  const getEventInfo = async () => {
    try {
      // 这里可以调用API获取比赛信息
      // const res = await API_GET_EVENT_INFO()
      // if (res.code === 1) {
      //   // 更新每个用户的比赛信息
      //   userList.value.forEach(user => {
      //     if (user.event_id) {
      //       const event = res.data.find(e => e.id === user.event_id)
      //       if (event) {
      //         user.eventInfo = event
      //       }
      //     }
      //   })
      // }
    } catch (error) {
      console.error('获取比赛信息失败:', error)
    }
  }

  // 根据ID获取用户信息
  const getUserInfoById = async (userId) => {
    try {
      // 这里可以调用API根据ID获取用户信息
      // const res = await API_GET_USER_INFO_BY_ID({ user_id: userId })
      // if (res.code === 1) {
      //   const userIndex = userList.value.findIndex(u => u.id === userId)
      //   if (userIndex !== -1) {
      //     updateUser(userIndex, res.data)
      //   } else {
      //     addUser(res.data)
      //   }
      // }
      console.log('获取用户信息，用户ID:', userId)
    } catch (error) {
      console.error('根据ID获取用户信息失败:', error)
    }
  }

  // 根据ID获取比赛信息
  const getEventInfoById = async (eventId) => {
    try {
      // 这里可以调用API根据ID获取比赛信息
      // const res = await API_GET_EVENT_INFO_BY_ID({ event_id: eventId })
      // if (res.code === 1) {
      //   // 更新所有用户的比赛信息
      //   userList.value.forEach(user => {
      //     if (user.event_id === eventId) {
      //       user.eventInfo = res.data
      //     }
      //   })
      // }
      console.log('获取比赛信息，比赛ID:', eventId)
    } catch (error) {
      console.error('根据ID获取比赛信息失败:', error)
    }
  }

  // 页面显示时获取参数
  onShow(() => {
    const pages = getCurrentPages() // 获取当前页面栈
    const currentPage = pages[pages.length - 1] // 获取当前页面
    console.log('currentPage', currentPage)

    const options = currentPage.options // 获取当前页面的参数
    const { user_id, event_id } = options
    
    if (user_id) {
      // 处理用户ID参数
      getUserInfoById(user_id)
    }
    
    if (event_id) {
      // 处理比赛ID参数
      getEventInfoById(event_id)
    }
  })

  onMounted(() => {
    getUserInfo()
    getEventInfo()
  })
</script>

<style lang="scss" scoped>
  @import './index.scss';
</style>